import { Injectable, EventEmitter } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  searchEvent: EventEmitter<ProductSearchParams> = new EventEmitter<ProductSearchParams>();
  private categories: string[] = ["图书", "科技", "电子"];
  constructor(public _http: Http) { }
  getProducts(): Observable<Product[]> {
    return this._http.get("/api/products/getall").map(res => res.json());
  }
  getProductById(id: number): Observable<Product> {

    return this._http.get('/api/products/getProductById?id=' + id).map(res => res.json());
  }
  getCommentsByProdId(id: number): Observable<ProdComment[]> {

    return this._http.get('/api/products/GetCommentsByProductId?id=' + id).map(res => res.json());
  }
  AddComment(arg0: any): any {
    //this.comments.unshift(arg0);
  }
  getAllCategories(): string[] {
    return this.categories;
  }
  getProductsBySearchParams(params: ProductSearchParams): Observable<Product[]> {
    return this._http.get('/api/products/getProductsBySearchParams', { search: this.encodeParams(params) }).map(res => res.json());
    //return this._http.get('/api/products/getProductsBySearchParams', JSON.stringify(params)).map(res => res.json());
  }
  encodeParams(arg0: ProductSearchParams): URLSearchParams {
    let params: URLSearchParams = new URLSearchParams();
    //console.log(Object.keys(arg0)
    //  .filter(key => !params[key]));
    Object.keys(arg0)
      .filter(key => !params[key])
      .forEach((key: string, index: number) => {
        console.log(key, arg0[key]);
        params.append(key, arg0[key]);
      });
    return params;
  }
}
export class ProductSearchParams {
  constructor(public title: string, public price: number, public category: string) { }
}
export class Product {
  constructor(public id: number,
    public prodName: string,
    public prodPrice: number,
    public prodDesc: string,
    public prodImg: string,
    public prodStars: number) {

  }
}
export class ProdComment {
  constructor(
    public id: number,
    public content: string,
    public date: Date,
    public userName: string,
    public rating: number) { }
}
